﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using UIT.Markup;
using UIT.Controls;
using UIT.Controls.Template;

namespace UIT.Converters
{
    public class TemplateConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return sourceType == typeof(string) || sourceType == typeof(Binding);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            if (value == null)
                return null;
            string stringValue = value as string;
            if (!string.IsNullOrEmpty(stringValue))
                return new DataTemplate() { Template = new TemplateContent() { VisualTree = new TextBlock() { Text = stringValue } } };
            Binding bindingValue = value as Binding;
            if (bindingValue != null)
                return GetTemplate(bindingValue);
            return null;
        }

        public static ITemplate GetTemplate(Binding bindingValue)
        {
            TextBlock tb = new TextBlock();
            tb.SetBinding("Text", bindingValue);
            return new DataTemplate() { Template = new TemplateContent() { VisualTree = tb }, IsBoundTemplate = true };
        }
    }
}
